package com.cmw.auntapp.core.util;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.cmw.auntapp.component.DateTextView;
import com.cmw.auntapp.component.SelectSpinner;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;

import androidx.appcompat.app.AppCompatActivity;
import lombok.SneakyThrows;

/**
 * @desc: 表单工具类
 * @author: chengmingwei
 * @date: 2021/4/29 8:09 PM
 * @contact: phone(微信同号):13922111489 / email: 340360491@qq.com
 */
public class FormUtil {
    public static final String TAG = "FormUtil";

    /**
     * 获取输入框元素的值，并以指定的对象返回
     * @param parent    父视图对象
     * @param viewIds   输入框元素ID数组
     * @return  返回布尔值 [true:有空值,false：无空值]
     */
    @SneakyThrows
    public static boolean isEmpty(AppCompatActivity parent, int[] viewIds){
        if (StringHandler.isEmpty(viewIds)) {
            Log.e(TAG, "参数：viewIds 不能为空!");
            return true;
        }

        for(int i = 0, count = viewIds.length; i < count; i++) {
            int viewId = viewIds[i];
            View fieldView = parent.findViewById(viewId);
            Object val = null;
            if (fieldView instanceof DateTextView) {
                DateTextView dateEditText = ((DateTextView)fieldView);
                val = dateEditText.getText().toString();
            } else if (fieldView instanceof EditText) {
                val = ((EditText)fieldView).getText().toString();
            } else if (fieldView instanceof RadioGroup) {
                int radioButtonId = ((RadioGroup)fieldView).getCheckedRadioButtonId();
                RadioButton radioButton = (RadioButton)parent.findViewById(radioButtonId);
                if (null == radioButton) {
                    val = null;
                } else {
                    val = (null == radioButton.getTag()) ? radioButton.getText().toString() : radioButton.getTag().toString();
                }
            }else if (fieldView instanceof SelectSpinner) {
                val =  ((SelectSpinner)fieldView).getValue();
            }
            if (null == val || val.equals("")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取输入框元素的值，并以指定的对象返回
     * @param parent    父视图对象
     * @param viewIds   输入框元素ID数组
     * @param fieldNames 对象字段名数组，必须与输入框元素ID一一对应
     * @param targetCls 要转成的目标对象
     * @param <T>
     * @return  目标对象
     */
    @SneakyThrows
    public static <T> T getValues(AppCompatActivity parent, int[] viewIds, String[] fieldNames, Class<T> targetCls){
        if (StringHandler.isEmpty(viewIds)) {
            Log.e(TAG, "参数：viewIds 不能为空!");
            return null;
        }
        if (StringHandler.isEmpty(fieldNames)){
            Log.e(TAG, "参数：fieldNames 不能为空!");
            return null;
        }
        if (viewIds.length != fieldNames.length) {
            Log.e(TAG, "参数：viewIds,fieldNames 两者的长度必须相同!");
            return null;
        }
        if (targetCls == null) {
            Log.e(TAG, "参数：targetCls 不能为空!");
            return null;
        }
        JSONObject dataJson = new JSONObject();
        for(int i = 0, count = viewIds.length; i < count; i++) {
            int viewId = viewIds[i];
            String fieldName = fieldNames[i];
            View fieldView = parent.findViewById(viewId);
            Object val = null;
            if (fieldView instanceof DateTextView) {
                DateTextView dateEditText = ((DateTextView)fieldView);
                val = dateEditText.getText().toString();
                //val = DateUtil.dateFormat(dateVal);
            } else if (fieldView instanceof EditText) {
                val = ((EditText)fieldView).getText().toString();
            } else if (fieldView instanceof RadioGroup) {
                int radioButtonId = ((RadioGroup)fieldView).getCheckedRadioButtonId();
                RadioButton radioButton = (RadioButton)parent.findViewById(radioButtonId);
                if (null == radioButton) {
                    val = null;
                } else {
                    val = (null == radioButton.getTag()) ? radioButton.getText().toString() : radioButton.getTag().toString();
                }
            }else if (fieldView instanceof SelectSpinner) {
                val =  ((SelectSpinner)fieldView).getValue();
            }
            if (null == val) continue;
            dataJson.put(fieldName, val);
        }
        T targetObj = FastJsonUtil.convertJsonToObj(dataJson, targetCls);
        return targetObj;
    }

    /**
     * 在UI上显示错误信息
     * @param parent
     * @param errInfo
     */
    public static void displayErrs(AppCompatActivity parent, Map<Integer, String> errInfo) {
        Set<Integer> keys = errInfo.keySet();
        for(Integer viewId : keys) {
            String errMsg = errInfo.get(viewId);
            View fieldView = parent.findViewById(viewId);
            if (null == fieldView) {
                Log.e(TAG, "元素ID："+ viewId +" 的View对象不存在!");
                break;
            }
            if (fieldView instanceof EditText) {
                EditText editText = ((EditText)fieldView);
                editText.setError(errMsg);
                editText.requestFocus();
                break;
            } else if (fieldView instanceof RadioGroup) {
                RadioGroup radioGroup = (RadioGroup)fieldView;
                radioGroup.requestFocus();
                Toast.makeText(parent, errMsg, Toast.LENGTH_LONG).show();
                break;
            } else if (fieldView instanceof DateTextView) {
                DateTextView editText = ((DateTextView)fieldView);
                editText.setError(errMsg);
                editText.requestFocus();
            } else if (fieldView instanceof SelectSpinner) {
                SelectSpinner selectSpinner =  ((SelectSpinner)fieldView);
                selectSpinner.setError(errMsg);
                selectSpinner.requestFocus();
                break;
            } else {
                Toast.makeText(parent, errMsg, Toast.LENGTH_LONG).show();
                fieldView.requestFocus();
            }
        }
    }

    public static void setValues(AppCompatActivity parent, JSONObject resultData, int[] viewIds) {
        for (int viewId : viewIds) {
            View view = parent.findViewById(viewId);
            if (null == view) {
                Log.e(TAG,"viewId = "+viewId +" 的元素对象在页面中找不到！");
                continue;
            }
            String tag = (String)view.getTag();
            if (TextUtils.isEmpty(tag)) {
                Log.e(TAG, "viewId:"+viewId +"的元素的 tag 属性值为空，无法进行赋值映射！");
                continue;
            }
            String filedVal = resultData.getString(tag);
            setValue(view, filedVal);
        }
    }


    public static void setValues(AppCompatActivity parent, JSONObject resultData, String[] fieldNames, int[] viewIds) {
        for(int i = 0, count = fieldNames.length; i < count; i++) {
            String fieldName = fieldNames[i];
            Integer viewId = viewIds[i];
            View view = parent.findViewById(viewId);
            if (null == view) {
                Log.e(TAG,"viewId = "+viewId +" 的元素对象在页面中找不到！");
                continue;
            }
            String filedVal = resultData.getString(fieldName);
            setValue(view, filedVal);
        }
    }

    public static void setValue(View fieldView, String val) {
        if (fieldView instanceof EditText) {
            EditText editText = ((EditText)fieldView);
            editText.setText(val);
        } else if (fieldView instanceof RadioGroup) {
            RadioGroup radioGroup = (RadioGroup)fieldView;
            radioGroup.clearCheck();
            View radioView = radioGroup.findViewWithTag(val);
            if (null == radioView) {
                return;
            }
            ((RadioButton)radioView).setChecked(true);
        } else if (fieldView instanceof DateTextView) {
            DateTextView editText = ((DateTextView)fieldView);
            editText.setText(val);
        } else if (fieldView instanceof SelectSpinner) {
            SelectSpinner selectSpinner =  ((SelectSpinner)fieldView);
            selectSpinner.setValue(val);
        } else if (fieldView instanceof TextView) {
            TextView textView =  ((TextView)fieldView);
            textView.setText(val);
        }else {
            Log.e(TAG,fieldView.toString() + " 未知的View对象，无法赋值!");
        }

    }
}
